package cn.gpdi.framework.controller;

import cn.gpdi.framework.annotation.FwIsOpenRequest;
import cn.gpdi.framework.dao.CommDAO;
import cn.gpdi.framework.pojo.CodeImage;
import cn.gpdi.framework.pojo.FwTextTransObject;
import cn.gpdi.framework.service.FwCommService;
import cn.gpdi.framework.util.CodeMakeUtil;
import cn.gpdi.framework.util.CommUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * 处理excel文件导入、解析。
 * 处理excel文件导出（下载）
 * 处理图片上传、下载
 * Created by 司徒鑫(QQ:156845600) on 2017/11/1.
 */
@Controller
@RequestMapping(value = "/fw")
public class FwCommController {

    @Resource
    CommDAO commDAO;

    @Autowired
    FwCommService fwCommService;
    @Autowired
    private HttpSession session;

    Logger logger = Logger.getLogger(FwCommController.class);

    /**
     * ajax请求：
     * 配置1 service：fw_service，fw_method
     * 配置2 mapperid：mapperid 必须遵循结尾为：_D ，_Q ，_U ，_I的规则；
     *
     * @param paramMap
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/doService.do")
    public Map doService(@RequestBody Map<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map rtnMap = new HashMap();
        Object rtnObj = null;

        if (!CommUtil.isEmpty(paramMap.get("fw_mapperid"))) {
            String mapperid = paramMap.get("fw_mapperid").toString().toUpperCase();
            Object param=paramMap.get("fw_param");
            rtnObj=fwCommService.dbExcute(mapperid,param) ;
        } else if (!CommUtil.isEmpty(paramMap.get("fw_service")) && !CommUtil.isEmpty(paramMap.get("fw_service"))) {
            String serviceName = paramMap.get("fw_service").toString();
            String method = paramMap.get("fw_method").toString();
            FwTextTransObject dto = new FwTextTransObject();
            dto.setRequest(request);  //设置请求
            dto.setResponse(response);    //设置响应
            dto.setSession(request.getSession());    //设置会话
            dto.setDataObject(paramMap.get("fw_param"));  //设置参数
            Object service = CommUtil.getBean(serviceName);
            Class cls = service.getClass();
            try {
                rtnObj = cls.getDeclaredMethod(method, FwTextTransObject.class).invoke(service, dto);
            } catch (InvocationTargetException e) {
                Throwable t = e.getTargetException();// 获取目标异常
                throw (Exception) t;
            }
        } else {

        }
        rtnMap.put("code", 1);    //1成功，0 失败
        rtnMap.put("data", rtnObj);
        //   rtnMap.put("session_id", session.getId());
        return rtnMap;

    }


    @RequestMapping(value = "/getImg.do")
    @ResponseBody
    /**
     * 根据本地路径获取图片
     * 经过response.getOutputStream返回
     */
    public Map createFolw(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        String img_url = "";    //数据库获取路径
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(img_url);
            os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            fis.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map rtnMap = new HashMap();
        rtnMap.put("code", 1);    //1成功，0 失败
        rtnMap.put("session_id", session.getId());   //
        rtnMap.put("msg", "");   //
        return rtnMap;
    }

    @RequestMapping(value = "/getClientAddress.do")
    @ResponseBody
    public Map getClientAddress(HttpServletRequest request) throws Exception {
        Map m = new HashMap();
        m.put("CLIENT_ADDRESS", request.getRemoteAddr());
        return m;
    }


    @RequestMapping(value = "/getIdentifyingCode.do", method = {RequestMethod.POST,RequestMethod.GET})
    //验证码生成
    public void VerificationCode( HttpServletResponse response) throws Exception {
        // 设置页面不缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 输出图象到页面
        CodeImage codeImage= CodeMakeUtil.getCode();
        ImageIO.write(codeImage.getImage(), "JPEG", response.getOutputStream());

        //存放到session中,后续用于校验。
        session.setAttribute("XXX",codeImage.getCode());
    }


    @RequestMapping(value = "/test.do")
    @ResponseBody
    @FwIsOpenRequest
    public Map test2(HttpServletRequest request) throws Exception {
        Map m = new HashMap();
        return m;
    }
}
